#!usr/bin/env python  
# -*- coding:utf-8 -*-
import logging
import datetime

from django.utils.deprecation import MiddlewareMixin
from bbd_admin.models import BlogCounts
from threading import Thread
from django.db.models import F

LOG = logging.getLogger(__name__)


class RequestControl(MiddlewareMixin):
    blank_url = ['article_detail', 'author_article']

    def process_request(self, request):
        real_path = 'http://' + request.get_host() + request.path

        def _update_count():
            blog_count = BlogCounts.objects.filter(
                create_date__month=datetime.datetime.now().month,
                url=real_path)
            if blog_count:
                blog_count.update(counts=F('counts') + 1)
            else:
                BlogCounts.objects.create(url=real_path, counts=1)

        for blank in self.blank_url:
            if blank in real_path:
                Thread(target=_update_count, args=()).start()
            continue
        meta = request.META
        path = meta['PATH_INFO']
        if 'article_detail' in path:
            LOG.warning('访问统计:%s,%s,%s' %
                        (path, meta['REMOTE_ADDR'], meta['HTTP_USER_AGENT']))
